﻿/**
 * Peter
 * Created by: Peter Development Team
 *    http://peter.codeplex.com/
 * 
 * GNU General Public License version 2 (GPLv2)
 *    http://peter.codeplex.com/license
 **/

using System.Collections.Generic;
using System.Linq;
using Peter.Common.Interfaces;
using Peter.Common.Services;
using Peter.Common.Utilities;
using Peter.Data;
using Peter.Properties;

namespace Peter.Logic
{
   /// <summary>
   /// Methods and properties used for searching.
   /// </summary>
   public class SearchAutoComplete : IPeterSearchAutoComplete
   {
      private OptionsGeneral m_General;

      /// <summary>
      /// Gets the general options.
      /// </summary>
      protected OptionsGeneral GeneralOptions
      {
         get
         {
            if (this.m_General == null)
            {
               var options = ServiceManager.Get<IPeterOptions> ();
               this.m_General = (OptionsGeneral)options.GetOptionPage ("General");
            }
            return this.m_General;
         }
      }

      /// <summary>
      /// Adds an item to the search history.
      /// </summary>
      /// <param name="searchItem">Search item to add to the history.</param>
      public void AddHistoryItem (string searchItem)
      {
         if (this.GeneralOptions != null)
         {
            if (!this.GeneralOptions.SearchHistory.Contains (searchItem))
               this.GeneralOptions.SearchHistory.Add (searchItem);

            while (this.GeneralOptions.SearchHistory.Count > Settings.Default.MaxSearchHistory)
               this.GeneralOptions.SearchHistory.RemoveAt (this.GeneralOptions.SearchHistory.Count - 1);
         }
      }

      /// <summary>
      /// Gets the list of auto complete items.
      /// </summary>
      /// <param name="filter">Text filter to apply.</param>
      /// <returns>Collection of auto complete items.</returns>
      public IEnumerable <string> GetAutoCompleteItems (string filter)
      {
         if (this.GeneralOptions != null)
         {
            var searchHistory = this.GeneralOptions.SearchHistory;
            foreach (var searchItem in searchHistory.Where (si => si.ContainsIgnoreCase (filter)))
            {
               yield return searchItem;
            }
         }
      }
   }
}
